package com.briup.searchengine.view.dao;

import com.briup.searchengine.view.bean.PageBean;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Hash;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.*;

@Repository
public class PageDao {
    public Set<PageBean> findPageByKW(String keyword, String tablename) throws IOException {
        Connection conn = DBUtil.conn;
        Table table = conn.getTable(TableName.valueOf(tablename));
        Scan scan = new Scan();
        Filter f = new RowFilter
                (CompareFilter.CompareOp.EQUAL,
                        new RegexStringComparator(".*" + keyword + ".*"));
        scan.setFilter(f);
        ResultScanner scanner = table.getScanner(scan);
        TreeSet<PageBean> set = new TreeSet<>(
                new Comparator<PageBean>() {
                    @Override
                    public int compare(PageBean o1, PageBean o2) {
                        return (int) (o2.getRank() * 1000 - o1.getRank() * 1000) == 0 ? o2.getTitle().compareTo(o1.getTitle()) : (int) (o2.getRank() * 1000 - o1.getRank() * 1000);
                    }
                });

        for (Result result : scanner) {
            byte[] row = result.getRow();
            String key = Bytes.toString(row);
            NavigableMap<byte[], byte[]> pages =
                    result.getFamilyMap(Bytes.toBytes("page"));
            for (byte[] u : pages.keySet()) {

                byte[] r = pages.get(u);
                String[] split = new String(r).split("[||]");
                PageBean bean = new PageBean();
                bean.setUri(Bytes.toString(u));
                bean.setKeyword(key);
                bean.setTitle(split[1]);
                bean.setContent(split[2]);
                bean.setRank(Double.parseDouble(split[0]));
                set.add(bean);
            }
        }
        return set;
    }
}
